package com.zk.sqservice.client;

import android.content.Context;
import android.os.MemoryFile;
import android.os.ParcelFileDescriptor;
import android.util.Log;

import com.zk.sqservice.ISqService;
import com.zk.sqservice.constant.DebugTag;

import java.io.FileDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author zgx
 * <p>
 * 通过binder把,MemoryFile 的 ParcelFileDescriptor 传到Service
 **/
public class ClientShareMem {


    public static final String TAG = DebugTag.TAG;
    private Context mContext;

    /**
     * 通过binder把,MemoryFile的ParcelFileDescriptor 传到Service
     **/
    private MemoryFile mServiceShareMemory;
    private ParcelFileDescriptor mParceServiceShareFile;

    private FileDescriptor mServiceShareFile;
    private int mFD = -1;
    /**
     * 内存大小
     */
    private static final int CONTENT_SIZE = 640 * 480;
    private byte[] mContent = new byte[CONTENT_SIZE];
    private byte[] mContentCopy = new byte[CONTENT_SIZE];

    private ISqService mISqService;


    public ClientShareMem(Context context) {
        mContext = context;
        createMemFile();
    }

    public void setISqService(ISqService s) {
        this.mISqService = s;
    }

    /***
     * 获得服务端的内存
     * **/
    private void createMemFile() {
        Log.i(TAG, "-createMemFile-");

        try {
            mServiceShareMemory = new MemoryFile(SqServiceProxy.SERVICE_PACKAGE
                    + System.currentTimeMillis(), mContent.length);

            //这种方式会有兼容性问题
            Method method = MemoryFile.class.getDeclaredMethod("getFileDescriptor");
            FileDescriptor fd = (FileDescriptor) method.invoke(mServiceShareMemory);

            mParceServiceShareFile = ParcelFileDescriptor.dup(fd);
            if (mServiceShareMemory != null) {
                mServiceShareMemory.allowPurging(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "createMemFile err : " + e.toString());
        }
    }

    public void dataFlow(int value) {
        //int 转 byte，填充到 mContent
        Arrays.fill(mContent, (byte) value);
        try {
            Log.d(TAG, "mIRemoteService  dataFlow start mContent: " + mContent[0]
                    + ", pid = " + android.os.Process.myPid());

            long time = System.currentTimeMillis();
            //MemoryFile
            mServiceShareMemory.writeBytes(mContent, 0, 0, mContent.length);
            Log.d(TAG, "mIRemoteService  dataFlow start mContentCopy: " + mContentCopy[0]);
            Log.d(TAG, "mIRemoteService  dataFlow writeBytes : " + (System.currentTimeMillis() - time));

            //MemoryFile获取ParcelFileDescriptor，通过Binder把ParcelFileDescriptor(int类型)传递到服务端
            //IRemoteService - 传递到服务端
            Log.d(TAG, "客户端传递数据 : " + value + "， 花费时间："
                    + (System.currentTimeMillis() - time));
            mISqService.dataFlow(mParceServiceShareFile, mContent.length);

            time = System.currentTimeMillis();
            Log.d(TAG, "mIRemoteService  dataFlow release : " + (System.currentTimeMillis() - time));
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "dataFlow err : " + e.toString());

        }
    }

    private void releaseShareMemory() {
        try {
            mParceServiceShareFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mServiceShareMemory == null) {
            return;
        }
        mServiceShareMemory.close();
        mServiceShareMemory = null;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        releaseShareMemory();
    }
}
